package com.activiti.basic.model;

import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author pisory
 * @version 1.0
 * @date 2020/4/5
 */
@Data
public class ResponseUtil {
    //重定向的url
    private  String redirectUrl;
    //返回
    private boolean back;
    //刷新页面
    private boolean refresh;

    public ResponseUtil() {
    }

    public static void write(HttpServletResponse response, Object o) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(o.toString());
        out.flush();
        out.close();
    }

    public static ResponseUtil buildResult(){
        return new ResponseUtil();
    }

    public WebResponse redirectUrl(String redirectUrl) {
        setRedirectUrl(redirectUrl);
        return success();
    }

    public WebResponse back() {
        setBack(true);
        return success();
    }

    public WebResponse refresh() {
        setRefresh(true);
        return success();
    }

    public static <T> WebResponse<T> success() {
        return new WebResponse(ResponseCodeConstant.RESPONSE_CODE_200, null, ResponseCodeConstant.SUCCESS_MESSAGE);
    }

    public static <T> WebResponse<T> success(T t) {
        return new WebResponse(ResponseCodeConstant.RESPONSE_CODE_200, t, ResponseCodeConstant.SUCCESS_MESSAGE);
    }

    public static <T> WebResponse<T> success(String message) {
        return new WebResponse(ResponseCodeConstant.RESPONSE_CODE_200, null, message);
    }

    public static <T> WebResponse<T> success(T t, String message) {
        return new WebResponse(ResponseCodeConstant.RESPONSE_CODE_200, t, message);
    }

    public static <T> WebResponse<T> success(String code, T t, String message) {
        return new WebResponse(ResponseCodeConstant.valueOf(code), t, message);
    }

    public static <T> WebResponse<T> fail() {
        return new WebResponse(ResponseCodeConstant.RESPONSE_CODE_500, null, ResponseCodeConstant.EXCEPTION_MESSAGE);
    }

    public static <T> WebResponse<T> fail(String message) {
        return new WebResponse(ResponseCodeConstant.RESPONSE_CODE_500, null, message);
    }

    public static <T> WebResponse<T> fail(T t, String message) {
        return new WebResponse(ResponseCodeConstant.RESPONSE_CODE_500, t, message);
    }

    public static <T> WebResponse<T> fail(String code, T t, String message) {
        return new WebResponse(ResponseCodeConstant.valueOf(code), t, message);
    }
}